import React from 'react'
import Reflux from 'reflux'
import ReactMixin from 'react-mixin'
import store from '../todo/store'
import actions from '../todo/actions'
import Popup from './popUp'
import '../../../less/style.less';


export default class Todo extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            show: false,
            text: ""
        }
    }

    //组件渲染完成后，通过action获取所有的数组，刷新绑定到this.state上
    componentDidMount() {
        actions.getAll();
    }

    add() {
        let item = this.refs.item.value;
        this.toggleShow();
        this.refs.item.value = '';
        actions.add(item)
    }

    remove(i) {
        actions.remove(i);
    }

    toggleShow() {
        this.setState({
            show: !this.state.show,
            text: this.refs.item.value,
        })

    }

    render() {
        //items用于乘放li的集合
        let items;
        if (this.state.list) {
            items = this.state.list.map((item, i) => {
                //设置key是因为react的diff算法，是通过key来计算最小变化的
                return <li key={i}>
                    {item.name}
                    <button onClick={this.remove.bind(this, i)}>remove</button>
                </li>
            })
        }
        return (
            <div className="todo-box">
                <input type="text" ref="item"/>
                <button onClick={this.toggleShow.bind(this)}>add</button>
                <ul>
                    {items}
                </ul>
                {
                    this.state.show && <div className="modal" onClick={this.toggleShow.bind(this)}></div>

                }
                {
                    this.state.show && <Popup add={this.add.bind(this)}
                                              text={this.state.text}
                                              toggleShow={this.toggleShow.bind(this)}
                    />
                }
            </div>
        )
    }
}

// ES6 mixin写法，通过mixin将store的与组件连接，功能是监听store带来的state变化并刷新到this.state
ReactMixin.onClass(Todo, Reflux.connect(store));
